var device=request("from")
var phone=request("phone")

var base64_01="";
var base64_02="";
var base64_03="";
var base64_04="";

//用于压缩图片的canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
//瓦片canvas
var tCanvas = document.createElement("canvas");
var tctx = tCanvas.getContext("2d");
var maxsize = 100 * 1024;

$(function(){
	//微信中检查phone是否绑定开始---------------------------------------------------
	if(device!="app"){
		if(sessionStorage.getItem("phone")!=""&&sessionStorage.getItem("phone")!=undefined&&sessionStorage.getItem("phone")!=null){
			phone=sessionStorage.getItem("phone");
		}
		else{
			var code=request("code");
			$.ajax({
			    url: DATA_URL+"checkwxbind",
			    data: "code="+code,
			    type: "post",
			    async: false,
			    dataType: 'json',
			    timeout: 5000,
			    success:function (data) {
			    	if(data.code=="0"){
			    		if(data.info.is_bind==1){
			    			phone=data.info.phone;
			    			sessionStorage.setItem("phone",data.info.phone);
			    		}
			    		else{
			    			var open_id=data.info.open_id;
			    			location.href="binding_phone.html?open_id="+open_id
			    		}
			    	}
					else{
						$("#prompt").text(data.msg);
			            $(".prompt").fadeIn(300,function(){
			                setTimeout(function(){$(".prompt").fadeOut(300)},3000)
			            })
					}
			    },
			    error:function () {
			    	$("#prompt").text("您的网络不给力哦~");
			        $(".prompt").fadeIn(300,function(){
			            setTimeout(function(){$(".prompt").fadeOut(300)},3000)
			        })
			    }
			});
		}
		
	}
	//微信中检查phone是否绑定结束-----------------------------------------------------------
	
	//获取图片
	$.ajax({
	    url: DATA_URL+"getauthpic",
	    data: "phone="+phone,
	    type: "post",
	    dataType: 'json',
	    timeout: 5000,
	    success:function (data) {
	    	if(data.code=="0"){
	    		if(data.info.jlz_pic!=""){
	    			$("#view_01").css("background-image","url("+data.info.jlz_pic+"?time="+new Date().getTime()+")");
	    		}
	    		if(data.info.xsz_pic!=""){
	    			$("#view_02").css("background-image","url("+data.info.xsz_pic+"?time="+new Date().getTime()+")");
	    		}
	    		if(data.info.sfz_pic!=""){
	    			$("#view_03").css("background-image","url("+data.info.sfz_pic+"?time="+new Date().getTime()+")");
	    		}
	    		if(data.info.jsz_pic!=""){
	    			$("#view_04").css("background-image","url("+data.info.jsz_pic+"?time="+new Date().getTime()+")");
	    		}
	    		
	    	}
			else{
				$("#prompt").text(data.msg);
	            $(".prompt").fadeIn(300,function(){
	                setTimeout(function(){$(".prompt").fadeOut(300)},3000)
	            })
			}
	    },
	    error:function () {
	    	$("#prompt").text("您的网络不给力哦~");
	        $(".prompt").fadeIn(300,function(){
	            setTimeout(function(){$(".prompt").fadeOut(300)},3000)
	        })
	    }
	});
	
	//选择图片
	document.getElementById("card_01").onchange = function () {
        get_base64("card_01","1");
    };
    document.getElementById("card_02").onchange = function () {
        get_base64("card_02","2");
    };
    document.getElementById("card_03").onchange = function () {
        get_base64("card_03","3");
    };
    document.getElementById("card_04").onchange = function () {
        get_base64("card_04","4");
    };
    function get_base64(id,index) {
        var file = document.getElementById(id).files[0];
        var r = new FileReader();  //本地预览
        r.onload = function(){
        	var base_str="";
	        var img = new Image();
	        img.src = r.result;
        	//如果图片大小小于100kb，则直接添加
	        if (r.result.length <= maxsize) {
	         	base_str=r.result;
	         	img = null;
	         	set_data()
	         	return;
	        }
			//图片加载完毕之后进行压缩
			if (img.complete) {
	          callback();
	        } else {
	          img.onload = callback;
	        }
	        function callback() {
	          var data = compress(img);
	          base_str=data;
	          set_data();
	          img = null;
	        }
        	function set_data(){
        		switch(index){
	        		case "1":
	        			$("#view_01").css("background-image","url("+base_str+")");
	        			base64_01=base_str;
	        		break;
	        		case "2":
	        			$("#view_02").css("background-image","url("+base_str+")");
	        			base64_02=base_str;
	        		break;
	        		case "3":
	        			$("#view_03").css("background-image","url("+base_str+")");
	        			base64_03=base_str;
	        		break;
	        		case "4":
	        			$("#view_04").css("background-image","url("+base_str+")");
	        			base64_04=base_str;
	        		break;
	        	}
	        	if(base64_01!=""||base64_02!=""||base64_03!=""||base64_04!=""){
	        		$(".upload").css({
	        			"background":"#3eb7f3",
	        			"color":"#fff"
	        		})
	        	}
	        	else{
	        		$(".upload").css({
	        			"background":"#dfdfdf",
	        			"color":"#bdbdbd"
	        		})
	        	}
        	}
        }
        r.readAsDataURL(file);    //Base64
    }
    
	//    使用canvas对大图片进行压缩
	function compress(img) {
	    var initSize = img.src.length;
	    var width = img.width;
	    var height = img.height;
	    //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
	    var ratio;
	    if ((ratio = width * height / 4000000) > 1) {
	      ratio = Math.sqrt(ratio);
	      width /= ratio;
	      height /= ratio;
	    } else {
	      ratio = 1;
	    }
	    canvas.width = width;
	    canvas.height = height;
	//        铺底色
	    ctx.fillStyle = "#fff";
	    ctx.fillRect(0, 0, canvas.width, canvas.height);
	    //如果图片像素大于100万则使用瓦片绘制
	    var count;
	    if ((count = width * height / 1000000) > 1) {
	      count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
	//            计算每块瓦片的宽和高
	      var nw = ~~(width / count);
	      var nh = ~~(height / count);
	      tCanvas.width = nw;
	      tCanvas.height = nh;
	      for (var i = 0; i < count; i++) {
	        for (var j = 0; j < count; j++) {
	          tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
	          ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
	        }
	      }
	    } else {
	      ctx.drawImage(img, 0, 0, width, height);
	    }
	    //进行最小压缩
	    var ndata = canvas.toDataURL('image/jpeg', 0.1);
	    console.log('压缩前：' + initSize);
	    console.log('压缩后：' + ndata.length);
	    console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
	    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
	    return ndata;
	}
  	//上传图片
    $(".upload").click(function(){
		if(base64_01==""&&base64_02==""&&base64_03==""&&base64_04==""){
            return false;
   		}
		console.log(base64_01)
		$.ajax({
		    url: DATA_URL+"upauthpic",
		    data: "phone="+phone+"&jlz="+encodeURIComponent(base64_01)+"&xsz="+encodeURIComponent(base64_02)+"&sfz="+encodeURIComponent(base64_03)+"&jsz="+encodeURIComponent(base64_04),
		    type: "post",
		    dataType: 'json',
		    timeout: 5000,
		    success:function (data) {
		    	if(data.code=="0"){
		    		console.log(data.info)
		    		$("#prompt").text("图片提交成功");
		            $(".prompt").fadeIn(300,function(){
		                setTimeout(function(){$(".prompt").fadeOut(300)},3000)
		            })
		            base64_01="";
					base64_02="";
					base64_03="";
					base64_04="";
					$(".upload").css({
	        			"background":"#dfdfdf",
	        			"color":"#bdbdbd"
	        		})
		    		//		if(device=="app"){
					//			location.href="qicheng://go_back"
					//		}
					//		else{
					//			location.replace("info_eidt.html?phone="+phone+"&from="+device)
					//		}
		    	}
				else{
					$("#prompt").text(data.msg);
		            $(".prompt").fadeIn(300,function(){
		                setTimeout(function(){$(".prompt").fadeOut(300)},3000)
		            })
				}
		    },
		    error:function () {
		    	$("#prompt").text("您的网络不给力哦~");
		        $(".prompt").fadeIn(300,function(){
		            setTimeout(function(){$(".prompt").fadeOut(300)},3000)
		        })
		    }
		});


	})
})
